package com.hmdp.utils;

import org.apache.coyote.http11.upgrade.UpgradeServletOutputStream;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class RedisIdWorker {
    private StringRedisTemplate stringRedisTemplate;
    private static final Long GEGIN_TIMESTAMP=1704067200L;
    private static final int COUNT_BITS=32;
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeTapm = epochSecond - GEGIN_TIMESTAMP;

        //生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        Long increment = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);
        //拼接返回

        return timeTapm<<COUNT_BITS|increment;
    }


}
